/**
 * @Description: 模拟服务-json-server启动
 * @Author: zhen
 * @Date: 2023-10-19
 */
const jsonServer = require('json-server');
const fs = require('fs');
const path = require('path');

const rewriteConfig = require('./rewrite');

const ip = '127.0.0.1';
const port = 3600;

const paths = ['/test', '/api/v1'];

const server = jsonServer.create();
const middlewares = jsonServer.defaults();

// 加载默认中间件 (logger, static, cors and no-cache)
server.use(middlewares);

server.use(jsonServer.bodyParser);

// 重写路由（似乎不起作用）
server.use(jsonServer.rewriter(rewriteConfig));

// 加载路由
paths.forEach((item) => {
  server.use(item, (req, res) => {
    const url = req.path.endsWith('/') ? req.path.slice(0, -1) : req.path;
    // const filePath = path.join(__dirname, './modules', item, `${url}.json`);
    const filePath = path.join(__dirname, './modules', `${url}.json`);
    // console.log(req.path, url, filePath, 'aaaaaa 加载路由');

    try {
      if (fs.existsSync(filePath)) {
        const responseData = fs.readFileSync(filePath, 'utf-8');
        res.jsonp(JSON.parse(responseData));
      } else {
        res.jsonp({
          statusCode: 500,
          message: `请在${filePath}下配置您的mock数据!`
        });
      }
    } catch (e) {
      res.jsonp({
        statusCode: 500,
        message: 'mock服务内部错误!'
      });
    }
  });
});

server.listen(
  {
    host: ip,
    port
  },
  () => {
    console.log(`JSON Server is running in http://${ip}:${port}`);
  }
);
